#include <time.h>
#include <string.h>
#include <stdarg.h>

#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/thread/mutex.hpp>

#include "trace_log.h"

using namespace std;
namespace utility
{
    LogFile::LogFile(string filename) :
                _filename(filename)
    {
    }

    ofstream* LogFile::create_file()
    {
        string filename = _filename;
        string path_str = _filename.substr(0, _filename.find_last_of("\\/") + 1);
        if (path_str == filename)
        {
            time_t t = time(0);
            char current_time[50];
            strftime(current_time, sizeof(current_time), "%Y-%m-%d.txt",localtime(&t));
            filename += current_time;
        }
        namespace fs = boost::filesystem;
        fs::path path(fs::initial_path());
        path = fs::system_complete(
                                   fs::path(path_str));

        if(!fs::exists(path))
        {
            if(!fs::create_directories(path))
                return NULL;
        }
        ofstream *ofile = new ofstream;
        ofile->open(filename.c_str(), ios::app);
        return ofile;
    }

    ofstream* LogFile::open()
    {
        ofstream *ofile = new ofstream;
        ofile->open(_filename.c_str(), ios::app);
        if(!*ofile)
        {
            return create_file();
        }
        else
        {
            return ofile;
        }
    }

    void LogFile::print(uint32_t ft, const char* format, ...)
    {
    #ifdef __MULTI_THREAD__
        boost::mutex::scoped_lock scoped_lock(_mutex);
    #endif
        ofstream* ofile = open();
        if(ofile != NULL && *ofile)
        {

            if ((ft & FMT_TIME) != 0)
            {
                time_t t = time(0);
                char current_time[50];
                strftime(current_time, sizeof(current_time), "[%Y-%m-%d %H:%M:%S]",localtime(&t));
                *ofile << current_time << " ";
            }
            else if((ft & FMT_DATE) != 0)
            {
                time_t t = time(0);
                char current_time[50];
                strftime(current_time, sizeof(current_time), "[%Y-%m-%d]",localtime(&t));
                //strftime(current_time, sizeof(current_time), "%Y%m%d %H:%M:%S",localtime(&t));
                *ofile << current_time << " ";
            }
            va_list args;
            va_start(args, format);
            char sprintf_buf[1024];
            vsprintf(sprintf_buf, format, args);
            va_end(args);
            *ofile << sprintf_buf << endl;
            ofile->close();
            delete ofile;
        }
    }
}
